<template>
  <div class="detail-pop">
    <div
      class="mask"
      @click.stop="closePop"
      @touchmove.prevent
      :style="{ height: maxHeight + 'px' }"
    />
    <transition name="open">
      <div class="pop" @touchmove.prevent :class="{'finish' : openDone}">
        <div class="main">
          <div class="desc">
            <div class="image" v-if="currentImage">
              <img v-lazy="currentImage" />
            </div>
            <div class="num">
              <p v-if="currentStock">库存: {{ +currentStock }}</p>
              <p v-if="detail.scoreCost">积分: <span v-if="currentPrice">{{ +currentPrice }}</span> + <span>￥{{ +detail.scoreCost.total }}</span></p>
              <p v-else>价格: <span v-if="currentPrice">￥{{ +currentPrice}}</span></p>
              <div class="total">
                <span class="sub" @click="subQuantity">-</span>
                <span class="quantity">{{ totalQuantity }}</span>
                <span class="add" @click="addQuantity">+</span>
              </div>
            </div>
          </div>
          <ul class="list">
            <li
              class="list-item"
              v-for="(item, index) in detail.skuName"
              :key="index"
            >
              <div class="name">
                {{ item.name }}
              </div>
              <ol class="value">
                <template v-for="(o, i) in item.values">
                  <li
                    class="value-item"
                    v-if="showAllSku || defineSkuList.includes(o.id)"
                    :key="i"
                    @click="selectValue(o)"
                    :class="{'active': o.selected, 'disable': o.disabled}"
                  >
                    {{o.value}}
                  </li>
                </template>
              </ol>
            </li>
          </ul>
          <div class="select" v-if="selectedText.length > 0 && totalPrice > 0">
            <p>
              您选择了:
              <span>{{ selectedText.join(', ') }}</span>
            </p>
            <p>
              总数量: <span>{{ totalQuantity }}</span>
              总金额: <span>￥{{ totalPrice }}</span>
              <template v-if="totalScore > 0">
                总积分: <span>{{ totalScore }}</span>
              </template>
            </p>
          </div>
          <div class="reset" @click="reset">重新选择</div>
        </div>
        <cube-button class="btn" primary @click="submit">{{ buttonText }}</cube-button>
      </div>
    </transition>
  </div>
</template>

<script>
/**
 * skuName  => all sku
 * sku      => set sku value
 *
 * defineSkuList => all defined values list
 */
export default {
  name: 'DetailPop',
  props: ['type', 'detail'],
  computed: {
    // mask height
    maxHeight() {
      return document.body.clientHeight
    },
    // all defined sku values list
    defineSkuList() {
      // if (this.detail.sku.length > 0) {
      //   const list = this.detail.sku.map(x => x.sku_values)
      //   return list.reduce((total, current) => {
      //     return total.concat(current)
      //   })
      // } else {
      //   return []
      // }
      const list = this.detail.sku.map(x => x.sku_values)
      return list.reduce((total, current) => {
        return total.concat(current)
      })
    },
    currentPrice() {
      let price = 0
      if (this.selectedList.length > 0) {
        price = this.whichSku.price
      } else {
        price = this.detail.price
      }
      return price
    },
    currentImage() {
      let image = ''
      if (this.selectedList.length > 0) {
        if (this.whichSku.image && this.whichSku.image.thumbnail_path) {
          image = this.whichSku.image.thumbnail_path
        }
      } else {
        if (this.detail.mainImage && this.detail.mainImage.thumbnail_path) {
          image = this.detail.mainImage.thumbnail_path
        }
      }
      return image
    },
    currentStock() {
      let stock = 0
      if (this.selectedList.length > 0) {
        stock = this.whichSku.stock
      } else {
        stock = this.detail.stock
      }
      return stock
    },
    totalPrice() {
      return this.currentPrice * this.totalQuantity
    },
    totalScore() {
      if (this.detail.scoreCost) {
        return this.detail.scoreCost.total * this.totalQuantity
      }
      return 0
    },
    buttonText() {
      let text = ''
      switch (this.type) {
        case 1:
          text = '添加到购物车'
          break
        case 2:
          text = '立即购买'
          break
        case 3:
          text = '发起拼团'
          break
        case 4:
          text = '参与此团'
          break
        case 5:
          text = '随机拼团'
          break
        default:
          text = ''
      }
      // if (this.detail.isGroup) {
      //   text = '立即拼团'
      // }
      return text
    }
  },
  watch: {
    // find product_sku id
    // 'detail.skuName': {
    //   handler(v) {
    //   },
    //   deep: true
    // },
    selectedSku: {
      handler(v) {
        // default first sku
        // if v.length > 1 => alert('请选择完整')
        if (v.length > 0) {
          const whichSku = v[0]
          this.whichSku = whichSku
        }
      },
      deep: true
    }
  },
  data() {
    return {
      // show all sku or define sku
      showAllSku: false,
      openDone: false,
      // [id, id]
      selectedList: [],
      // [{id, text}]
      selectedText: [],
      // if selectedSku.length > 1, maybe Choice is not complete
      // [{}, {}]
      selectedSku: [],
      // selectedSku[0]
      whichSku: {},
      totalQuantity: 1
    }
  },
  methods: {
    subQuantity() {
      if (this.totalQuantity > 1) {
        this.totalQuantity--
      }
    },
    addQuantity() {
      if (this.totalQuantity < this.currentStock) {
        this.totalQuantity++
      }
    },
    closePop() {
      this.reset()
      this.$emit('closePop')
    },
    submit() {
      if (this.selectedList.length < 1) {
        return this.$createToast({
          type: 'correct',
          txt: '请选择规格',
          time: 700,
          zIndex: 99999
        }).show()
      }
      if (this.selectedSku.length > 1) {
        return this.$createToast({
          type: 'correct',
          txt: '请选择完整',
          time: 700,
          zIndex: 99999
        }).show()
      }
      let emit
      switch (this.type) {
        case 1:
          emit = 'addCart'
          break
        case 2:
          emit = 'buy'
          break
        case 3:
          emit = 'createGroup'
          break
        case 4:
          emit = 'joinGroup'
          break
        case 5:
          emit = 'randomGroup'
          break
        default:
          emit = ''
      }
      if (emit.length > 0) {
        if (this.totalQuantity > this.currentStock) {
          return this.$createToast({
            type: 'correct',
            txt: '库存不足',
            time: 500
          }).show()
        }
        this.$emit(emit, {
          quantity: this.totalQuantity,
          price: this.currentPrice,
          score_cost: this.detail.scoreCost ? this.detail.scoreCost.total : 0,
          product_sku_id: this.whichSku.id,
          selected_sku_value: this.selectedList,
          selected_sku_text: this.selectedText
        })
      }
      this.closePop()
    },
    selectedValues(appendText = false) {
      const list = []
      this.detail.skuName.forEach(x => {
        x.values.forEach(y => {
          if (y.selected) {
            if (appendText) {
              list.push({ id: y.id, text: y.value })
            } else {
              list.push(y.id)
            }
          }
        })
      })
      return list
    },
    reset() {
      this.selectedList = []
      this.selectedText = []
      this.detail.skuName.forEach(x => {
        x.values.forEach(y => {
          this.$set(y, 'selected', undefined)
          this.$set(y, 'disabled', undefined)
        })
      })
    },
    /**
     * select
     */
    selectValue(o) {
      if (o.disabled && this.detail.skuName.length > 1) {
        return
      }
      // 1. myself
      let skuNameIndex, selected
      this.detail.skuName.forEach((x, index) => {
        x.values.forEach(y => {
          if (y.id === o.id) {
            this.$set(o, 'selected', !o.selected)
            skuNameIndex = index
            selected = o.selected
          }
        })
      })
      // 2. level
      if (skuNameIndex !== undefined) {
        this.detail.skuName[skuNameIndex].values.forEach(x => {
          if (selected && x.id !== o.id) {
            this.$set(x, 'selected', undefined)
          }
        })
      }
      // 3. admin set
      const selectedValues = this.selectedValues(true)
      const list = this.detail.sku.filter(x => selectedValues.every(y => x.sku_values.includes(y.id)))
      this.selectedSku = list
      const listValues = []
      list.forEach(x => {
        x.sku_values.forEach(y => {
          listValues.push(y)
        })
      })
      this.detail.skuName.forEach(x => {
        x.values.forEach(y => {
          if (!listValues.includes(y.id)) {
            this.$set(y, 'disabled', true)
          } else {
            this.$set(y, 'disabled', undefined)
          }
        })
      })
      // 4 selected display
      this.selectedText = selectedValues.map(x => x.text)
      this.selectedList = selectedValues.map(x => x.id)
    }
  },
  created () {
    // open anim
    setTimeout(() => {
      this.openDone = true
    }, 50)
  }
}
</script>

<style scoped lang="stylus">
.detail-pop
  background red
  .mask
    position absolute
    background black
    left 0
    bottom 0
    width 100%
    z-index 99
    opacity 0.6
  .pop
    background $background_color
    min-height 0
    width 100%
    position absolute
    left 0
    bottom 0
    z-index 99999
    transition: all 0.2s linear
    opacity 0.3
    border-top-left-radius 15px
    border-top-right-radius 15px
    box-sizing border-box
    overflow hidden
    padding-bottom 50px
    // open animation
    &.finish
      min-height 500px
      opacity 1
    .btn
      position absolute
      left 0
      bottom 0
    .main
      margin 10px
      padding 10px
      position relative
      .reset
        position absolute
        right 0
        top 0
        background $main_color
        padding 7.5px 15px
        border-radius 5px
        color white
        font-weight 700
      .desc
        display flex
        justify-content space-between
        .image
          width 100px
        .num
          flex 1
          padding 5px 10px
          p
            height 22px
            line-height 22px
            text-align left
            font-size 14px
            span
              color red
              font-weight 700
              font-size 16px
          .total
            height 50px
            display flex
            justify-content start
            align-items center
            span
              padding 7.5px 10px
              //background #ccc
              font-size 16px
              border-radius 5px
              &.quantity
                padding 7.5px 20px
                background $background_color
      .list
        text-align left
        margin-top 10px
        .list-item
          margin-bottom 20px
          .name
            font-size 14px
            font-weight 700px
          .value
            margin 10px
            .value-item
              display inline-block
              background #ccc
              margin-right 15px
              margin-bottom 15px
              padding 7.5px 15px
              border-radius 5px
              &.active
                background $main_color
              &.disable
                background #eee
      .select
        text-align left
        p
          height 25px
          span
            color red
</style>
